package com.uniview.web.contorller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.uniview.entity.po.LoginLog;
import com.uniview.service.LoginLogService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.uniview.base.BaseController;
import com.uniview.entity.po.Employees;
import com.uniview.entity.vo.ResultMessage;
import com.uniview.filter.UnSessionFilter;
import com.uniview.plugins.workplus.UserCredentialsOperations;
import com.uniview.service.EmployeesService;

import java.util.Base64;
import java.util.Date;

@Controller
@RequestMapping(value = "/admin")
public class LoginController extends BaseController {

	Logger logger = Logger.getLogger(LoginController.class);

	@Autowired
	private EmployeesService employeesService;

	@Autowired
	private UserCredentialsOperations userCredentialsOperations;

	@Autowired
	private LoginLogService loginLogService;

	@Value("#{configProperties['uniview.superAdmin']}")
	private String superAdmin;

	@Value("#{configProperties['uniview.adminName']}")
	private String adminName;

	@Value("#{configProperties['uniview.adminDept']}")
	private String adminDept;

	@Value("#{configProperties['uniview.adminPwd']}")
	private String adminPwd;

	@RequestMapping(value = "/login")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("login");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}

	@RequestMapping(value = "/doLogin")
	@ResponseBody
	public ResultMessage login(HttpServletRequest request, HttpServletResponse response) {
		try {
			String userName = ServletRequestUtils.getStringParameter(request, "userName");
			String password = ServletRequestUtils.getStringParameter(request, "password");

			if (superAdmin.toUpperCase().equals(userName.toUpperCase())) {
				// 判断是否是超级管理员
				boolean flag = userCredentialsOperations.verify(userName.toUpperCase(), password);
				if (flag || (this.adminPwd.equals(password))) {
					Employees emp = new Employees();
					emp.seteId(0);
					emp.setCreatedDate(new Date());
					emp.setEmpCode(superAdmin);
					emp.setEmpName(adminName);
					emp.setOrgName(adminDept);
					HttpSession session = request.getSession();
					session.setAttribute("employees", emp);
					// 下发一个令牌给登录用户
					String token = emp.getEmpCode() + System.currentTimeMillis();
					token = Base64.getEncoder().encodeToString(token.getBytes());
					session.setAttribute("token", token);
					String SID = session.getId();
					UnSessionFilter.sessionMap.put(SID, session);
					LoginLog loginLog = new LoginLog(emp.geteId(), new Date(), emp.getEmpName());// 用户登录日志
					loginLogService.saveLoginLog(loginLog); // 记录用户登录日志
					return getResult("成功", true, token);
				} else {
					return getResult("用户名密码错误", false);
				}
			} else {
				Employees emp = employeesService.findEmployeesByName(userName);
				if (emp != null) {
					LoginLog loginLog = new LoginLog(emp.geteId(), new Date(), emp.getEmpName());// 用户登录日志
					if (emp.getEmType() == 0) {
						// 走内部AD服务器认证
						// 调用接口校验用户信息
						boolean flag = true;
//						boolean flag = userCredentialsOperations.verify(userName.toUpperCase(), password);
						if (flag) {
							HttpSession session = request.getSession();
							session.setAttribute("employees", emp);
							// 下发一个令牌给登录用户
							String token = emp.getEmpCode() + System.currentTimeMillis();
							token = Base64.getEncoder().encodeToString(token.getBytes());
							session.setAttribute("token", token);
							String SID = session.getId();
							UnSessionFilter.sessionMap.put(SID, session);
							loginLogService.saveLoginLog(loginLog); // 记录用户登录日志
							return getResult("成功", true, token);
						} else {
							logger.error("===============用户校验失败！！");
							return getResult("用户名密码错误", false);

						}
					} else {
						// 走服务合作单点登录
						loginLogService.saveLoginLog(loginLog); // 记录用户登录日志
					}
				} else {
					logger.error("===============用户不存在！！");
					return getResult("用户名密码错误", false);
				}
			}
		} catch (Exception e) {

		}

		return getResult("用户名密码错误", false);
	}

	/**
	 * 退出登录
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("outLogin")
	public void outLogin(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		session.invalidate();
		try {
			response.sendRedirect(request.getContextPath() + "/admin/login");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
